// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成
package com.fowo.api.datainterface.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.R;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.datainterface.entity.Datainterface;
import com.fowo.api.datainterface.model.DatainterfaceSearchParamPo;
import com.fowo.api.datainterface.model.DatainterfaceVo;
import com.fowo.api.datainterface.service.DatainterfaceService;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Tag(name = "接口")
@RequestMapping("/api/datainterface")
@RestController
public class DatainterfaceController {

    @Resource
    private DatainterfaceService service;
    @Resource
    private DatainterfaceService datainterfaceService;
    @Resource
    private SysSerialService sysSerialService;

    @Operation(summary = "查询结果")
    @GetMapping
    public R<List<Datainterface>> search(
            DatainterfaceSearchParamPo search
    ) {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        if (jwtUserInfo != null) {
//            search.setCurrentUserId(jwtUserInfo.getUserId());
        }
        return R.data(service.search(search));
    }

    @Operation(summary = "查询最后更新时间")
    @GetMapping("lastUpdateTime")
    public R<Date> searchLastUpdateTime(DatainterfaceSearchParamPo search) {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        if (jwtUserInfo != null) {
//            search.setCurrentUserId(jwtUserInfo.getUserId());
        }
        return R.data(service.searchLastUpdateTime(search));
    }

    @Operation(summary = "获取分页查询结果")
    @GetMapping("page")
    public R<Page<Datainterface>> getPage(
            DatainterfaceSearchParamPo search
    ) {
        JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
        if (jwtUserInfo != null) {
//            search.setCurrentUserId(jwtUserInfo.getUserId());
        }
        return R.data(service.pageSearch(search));
    }

    @Operation(summary = "获取详情")
    @GetMapping("{id}")
    public R<DatainterfaceVo> getVoById(@PathVariable Long id) {
        return R.data(() -> service.getVoById(id));
    }

    @Operation(summary = "获取请求参数相关的编号列表")
    @GetMapping("request-params/{texts}/ids")
    public R<List<Long>> getIdsByRequestParams(@PathVariable String texts) {
        List<String> nameList = Arrays
                .stream(texts.split(","))
                .collect(Collectors.toList());
        return R.data(() -> service.getIdsByRequestParams(nameList));
    }

    @Operation(summary = "获取编号相关的请求参数列表")
    @GetMapping("request-params/{ids}")
    public R<List<String>> getVoById(@PathVariable String ids) {
        List<Long> idList = Arrays
                .asList(ids.split(","))
                .stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        return R.data(() -> service.getRequestParamsByIds(idList));
    }

    @PreAuthorize("@am.canAccess('datainterfaceCreate')")
    @Operation(summary = "新增")
    @PostMapping
    public R<Long> create(@Validated @RequestBody DatainterfaceVo model) {
        return R.data(() -> service.create(model));
    }

    @PreAuthorize("@am.canAccess('datainterfaceEdit')")
    @Operation(summary = "更新")
    @PutMapping
    public R update(@RequestBody DatainterfaceVo model) {
        return R.run(() -> service.update(model));
    }

    @PreAuthorize("@am.canAccess('datainterfaceEdit')")
    @Operation(summary = "编辑更新")
    @PutMapping("edit")
    public R updateForEdit(@RequestBody DatainterfaceVo model) {
        return R.run(() -> service.updateForEdit(model));
    }

    @PreAuthorize("@am.canAccess('datainterfaceDelete')")
    @Operation(summary = "删除")
    @DeleteMapping("{id}")
    public R delete(@PathVariable Long id) {
        return R.run(() -> service.delete(id));
    }

    @PreAuthorize("@am.canAccess('datainterfaceDelete')")
    @Operation(summary = "批量删除")
    @DeleteMapping("batch")
    public R batchDelete(@RequestBody IdListPo po) {
        return R.run(() -> service.batchDelete(po.getIds()));
    }


    @Operation(summary = "接口数据预览")
    @GetMapping("preview/{id}")
    public R<Object> getPreviewById(@PathVariable Long id, @RequestBody(required = false) Map currentParamsMap) {
        try {
            if (MapUtil.isNotEmpty(currentParamsMap)){
                currentParamsMap = MapUtil.removeAny(currentParamsMap, "_t");
            }
            Object o = datainterfaceService.executeInterface(id, null, null, JsonUtil.getJsonToBeanSafe(currentParamsMap, JSONObject.class), null);
            return R.data(o);
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }

    }

    @Operation(summary = "接口数据获取")
    @PostMapping("preview/{encode}")
    public R<Object> getPreviewByEncode(@PathVariable String encode, @RequestBody(required = false) Map currentParamsMap){
        try {
            if (MapUtil.isNotEmpty(currentParamsMap)){
                currentParamsMap = MapUtil.removeAny(currentParamsMap, "_t");
            }
            Object o = datainterfaceService.executeInterface(null, encode, null, JsonUtil.getJsonToBeanSafe(currentParamsMap, JSONObject.class), null);
            return R.data(o);
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }

    }

    @Operation(summary = "接口入口,内部调用", hidden = true)
    @RequestMapping(value = "dynamic/{route}", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT})
    public Object route(@PathVariable String route, @RequestBody(required = false) Object model) {
        try {
            Object res = datainterfaceService.executeInterface(null, null, route, model, null);
            return res;
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }
    }


    @Operation(summary = "获取单号")
    @GetMapping("getNumber")
    public R<String> getNumber() throws Exception {
        try {
            String number = sysSerialService.getNewSerial(new NewSerialRequest(null, "Datainterface.encode"));
            return R.data(number);
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }
    }

    @Operation(summary = "拷贝")
    @GetMapping("copy/{id}")
    public R<String> copy(@PathVariable Long id) throws Exception {
        try {
            Boolean number = datainterfaceService.copy(id);
            return R.ok(number);
        } catch (Exception ex) {
            return R.fail("发生异常：" + ExceptionUtil.getSimpleMessage(ex));
        }
    }


}
